import axios from 'axios'

const state = {
  token: localStorage.getItem('token') || '',
  userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}')
}

const mutations = {
  SET_TOKEN(state, token) {
    state.token = token
    localStorage.setItem('token', token)
  },
  SET_USER_INFO(state, userInfo) {
    state.userInfo = userInfo
    localStorage.setItem('userInfo', JSON.stringify(userInfo))
  },
  CLEAR_USER_DATA(state) {
    state.token = ''
    state.userInfo = {}
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
  }
}

const actions = {
  // 登录
  async login({ commit }, loginForm) {
    try {
      const { data } = await axios.post('/user/login', loginForm)
      if (data.code === 0) {
        commit('SET_TOKEN', data.data.token)
        commit('SET_USER_INFO', data.data.userInfo)
        return Promise.resolve(data)
      } else {
        return Promise.reject(data.message)
      }
    } catch (error) {
      return Promise.reject(error)
    }
  },
  
  // 获取用户信息
  async getUserInfo({ commit, state }) {
    if (!state.token) {
      return Promise.reject('未登录')
    }
    try {
      const { data } = await axios.get('/user/info')
      if (data.code === 0) {
        commit('SET_USER_INFO', data.data)
        return Promise.resolve(data.data)
      } else {
        return Promise.reject(data.message)
      }
    } catch (error) {
      return Promise.reject(error)
    }
  },
  
  // 登出
  logout({ commit }) {
    commit('CLEAR_USER_DATA')
    return Promise.resolve()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
} 